package com.inno.screenrecorder;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.PathUtils;
import com.inno.screenrecordhelper.FloatingWindowHelper;
import com.inno.screenrecordhelper.ScreenRecordManager;
import com.inno.screenrecordhelper.VideoRecordManager;

/**
 * @author (zijie)
 * @datetime 2021-11-18 08:54
 * @email hezijie@inno-cn.cn
 * @detali：
 */
public class FloatWindowService extends Service {

    private static final String TAG = "111";
    public static boolean isStart = false;
    public static final String ACTION_AUDIO = "Audio";//录音
    public static final String ACTION_AUDIO_VIDEO = "Audio_Video";//录音录像
    public static final String ACTION_AUDIO_VIDEO_SCREEN = "Audio_Video_Screen";//录音录像录屏
    public static final String ACTION_AUDIO_SCREEN = "Audio_Screen";//录音录屏
    public static final String STOP_AUDIO = "stop_audio";//停止录音
    public static final String STOP_VIDEO = "stop_video";//停止录像
    public static final String STOP_SCREEN = "stop_screen";//停止录屏
    public static final String STOP_VIDEO_SCREEN = "stop_video_screen";//停止录音录像录屏
    private FloatingWindowHelper mFloatingWindowHelper;
    private View mExampleViewA;
    private ConstraintLayout mExampleViewB;
    private SurfaceView surfaceView;
    private String curAction;
    private VideoRecordManager videoRecordManager;
    private ScreenRecordManager screenRecordHelper = null;
    public static final int REQUEST_CODE = 1024;
    public static final int REQUEST_CODE_ALL = 1025;
    /**
     * 监听本地广播,点击事件
     */

    private BroadcastReceiver mLocalBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive: " + intent.getAction() );
            switch (intent.getAction()) {
                case ACTION_AUDIO:
                    if (!TextUtils.isEmpty(curAction))
                        switch (curAction) {
                            case ACTION_AUDIO:
                                break;
                            case ACTION_AUDIO_VIDEO:
                                videoRecordManager.stop(VideoRecordManager.VIDEO_RECORD);
                                mFloatingWindowHelper.removeView(mExampleViewB);
                                break;
                            case ACTION_AUDIO_VIDEO_SCREEN:
                                stopScreenShot();
                                stopVideo();
                                break;
                            case ACTION_AUDIO_SCREEN:
                                stopScreenShot();
                                break;
                        }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //如果当前不是录音状态
                            if (!TextUtils.equals(curAction, ACTION_AUDIO)) {
                                if (!mFloatingWindowHelper.contains(mExampleViewA)) {
                                    mFloatingWindowHelper.addView(mExampleViewA, 100, 100, true);
                                }
                                videoRecordManager.record(VideoRecordManager.AUDIO_RECORD);
                                curAction = ACTION_AUDIO;
                            }
                        }
                    },100);

                    break;
                case ACTION_AUDIO_VIDEO:
                    if (!TextUtils.isEmpty(curAction))
                        switch (curAction) {
                            case ACTION_AUDIO:
                                videoRecordManager.stop(VideoRecordManager.AUDIO_RECORD);
                                break;
                            case ACTION_AUDIO_VIDEO:
                                break;
                            case ACTION_AUDIO_VIDEO_SCREEN:
                                stopScreenShot();
                                curAction = ACTION_AUDIO_VIDEO;
                                break;
                            case ACTION_AUDIO_SCREEN:
                                stopScreenShot();
                                break;
                        }
                    //如果从录像录屏切换过来，则直接关闭录屏就行了，不用重新开启录像
                    if (!TextUtils.equals(curAction,ACTION_AUDIO_VIDEO))
                        startVideo(ACTION_AUDIO_VIDEO);

                    break;
                case ACTION_AUDIO_SCREEN: //录屏
                    if (!TextUtils.isEmpty(curAction))
                        switch (curAction) {
                            case ACTION_AUDIO:
                                stopAudio();
                                break;
                            case ACTION_AUDIO_VIDEO:
                                stopVideo();
                                break;
                            case ACTION_AUDIO_VIDEO_SCREEN:
                                stopVideo();
                                curAction = ACTION_AUDIO_SCREEN;
                                break;
                            case ACTION_AUDIO_SCREEN:
                                break;
                        }
                    if (!TextUtils.equals(ACTION_AUDIO_SCREEN,curAction) && !TextUtils.equals(ACTION_AUDIO_VIDEO_SCREEN,curAction))
                        startScreenShot(intent,ACTION_AUDIO_SCREEN);
                    break;
                case ACTION_AUDIO_VIDEO_SCREEN: //录音录屏，录像
                    if (!TextUtils.isEmpty(curAction))
                        switch (curAction) {
                            case ACTION_AUDIO:
                                stopAudio();
                                break;
                            case ACTION_AUDIO_VIDEO:
                                stopVideo();
                                break;
                            case ACTION_AUDIO_VIDEO_SCREEN:
                                break;
                            case ACTION_AUDIO_SCREEN:
                                break;
                        }
                    //如果是从录像切换过来，则不用重新开启录像，只需要开启录屏就行了
                    if (!TextUtils.equals(curAction,ACTION_AUDIO_VIDEO))
                        startVideo(ACTION_AUDIO_VIDEO_SCREEN);
                    if (!TextUtils.equals(curAction,ACTION_AUDIO_SCREEN))
                        startScreenShot(intent,ACTION_AUDIO_VIDEO_SCREEN);
                    curAction = ACTION_AUDIO_VIDEO_SCREEN;

                    break;

                case STOP_AUDIO:
                    stopAudio();
                    curAction = "";
                    break;
                case STOP_VIDEO:
                    stopVideo();
                    curAction = "";
                    break;
                case STOP_SCREEN:
                    stopScreenShot();
                    curAction = "";
                    break;

            }
//            if (ACTION_AUDIO.equals(intent.getAction())) {
//                onClick();
//            }
        }
    };
    private View screenFloat;
    private TextView tvScreenTime;
    private void stopScreenShot(){
        screenRecordHelper.stopRecord();
        mFloatingWindowHelper.removeView(screenFloat);
    }
    private void startScreenShot(Intent intent,String type) {
        if (!mFloatingWindowHelper.contains(screenFloat)) {
            mFloatingWindowHelper.addView(screenFloat, 1920, 0, true);
        }
        int code = intent.getIntExtra("code", -1);
        Intent data = intent.getParcelableExtra("data");
        screenRecordHelper.startRecord(code,data);
        curAction = type;
    }

    private void startVideo(final String type) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //如果当前不是录像状态
                if (!TextUtils.equals(curAction, ACTION_AUDIO_VIDEO)) {
                    if (!mFloatingWindowHelper.contains(mExampleViewB)) {
                        mFloatingWindowHelper.addView(mExampleViewB, 1920, 100, true);
                    }
                    if (!mFloatingWindowHelper.contains(mExampleViewA)) {
                        mFloatingWindowHelper.addView(mExampleViewA, 100, 100, true);
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            videoRecordManager.record(VideoRecordManager.VIDEO_RECORD);
                            curAction = type;
                        }
                    }, 100);
                }
            }
        }, 100);
    }

    private void stopVideo() {
        videoRecordManager.stop(VideoRecordManager.VIDEO_RECORD);
        mFloatingWindowHelper.removeView(mExampleViewB);
        mFloatingWindowHelper.removeView(mExampleViewA);

    }

    private void stopAudio() {
        videoRecordManager.stop(VideoRecordManager.AUDIO_RECORD);
        mFloatingWindowHelper.removeView(mExampleViewA);
    }

    private TextView tvRecordTime;



    @Override
    public void onCreate() {
        super.onCreate();
        isStart = true;
        //注册监听本地广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_AUDIO);
        intentFilter.addAction(ACTION_AUDIO_VIDEO);
        intentFilter.addAction(ACTION_AUDIO_VIDEO_SCREEN);
        intentFilter.addAction(ACTION_AUDIO_SCREEN);
        intentFilter.addAction(STOP_AUDIO);
        intentFilter.addAction(STOP_VIDEO);
        intentFilter.addAction(STOP_SCREEN);
        LocalBroadcastManager
                .getInstance(this)
                .registerReceiver(mLocalBroadcastReceiver, intentFilter);

        mFloatingWindowHelper = new FloatingWindowHelper(this);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        mExampleViewA = layoutInflater.inflate(R.layout.widget_test_view, null, false);
        tvRecordTime = mExampleViewA.findViewById(R.id.tv_record_time);
        mExampleViewB = (ConstraintLayout) layoutInflater.inflate(R.layout.widget_test_view_b, null, false);
        surfaceView = mExampleViewB.findViewById(R.id.surface);

        screenFloat = layoutInflater.inflate(R.layout.screen_float_view, null, false);
        tvScreenTime = screenFloat.findViewById(R.id.tv_record_time);
//        onClick();
        init();
        Log.e(TAG, "onCreate: ");
    }

    public void init() {

        if (screenRecordHelper == null) {
            screenRecordHelper = new ScreenRecordManager(tvScreenTime,this, new ScreenRecordManager.OnVideoRecordListener() {
                @Override
                public void onBeforeRecord() {

                }

                @Override
                public void onStartRecord() {
                }

                @Override
                public void onCancelRecord() {
                }

                @Override
                public void onEndRecord() {
                }
            }, PathUtils.getExternalStoragePath() + "/nanchen");

        }
        if (null == videoRecordManager)
            videoRecordManager = new VideoRecordManager(tvRecordTime, surfaceView, new VideoRecordManager.OnVideoRecordListener() {
                @Override
                public void onBeforeRecord() {

                }

                @Override
                public void onStartRecord() {

                }

                @Override
                public void onCancelRecord() {

                }

                @Override
                public void onEndRecord() {

                }
            });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager
                .getInstance(this)
                .unregisterReceiver(mLocalBroadcastReceiver);
        mFloatingWindowHelper.destroy();
        isStart = false;
        videoRecordManager.onDestroy();
        videoRecordManager = null;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private NotificationManager notificationManager;
    private Notification notification;
    private NotificationChannel notificationChannel;
    private final static String NOTIFICATION_CHANNEL_ID = "CHANNEL_ID";
    private final static String NOTIFICATION_CHANNEL_NAME = "录屏录像";
    private final static int FOREGROUND_ID = 1;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ");
        //在Android o之后app每发送一个通知都需要依附一个NotificationChannel
        notificationChannel = new NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                NOTIFICATION_CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH
        );
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
        intent = new Intent(getApplicationContext(), MainActivity2.class);  //点击通知栏后想要被打开的页面MainActivity.class
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);  //点击通知栏触发跳转
        notification = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("录屏录像功能正在使用")
                .setContentText("点击即可了解详情或停止应用")
                .setContentIntent(pendingIntent)
                .build();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(FOREGROUND_ID, notification);
        return super.onStartCommand(intent, flags, startId);
    }
}
